class JsonURLRequired < StandardError
end

class StationListUnavailable < StandardError
end

module AltaBikes
  class City

    attr_accessor :json_url, :stations_root, :stations, :updated_at

    def initialize(configuration = AltaBikes.configuration)
      raise JsonURLRequired if configuration.json_url.nil?
      @json_url      = configuration.json_url
      @stations_root = configuration.stations_root
      @station_list  = []
    end

    def station(id)
      return nil unless id
      stations.select { |station| station.details[:id] == id }.first
    end

    def stations
      @stations ||= fetch_stations
    end

    def refresh_stations
      @stations = nil
      stations
    end

    private

    def fetch_stations
      @updated_at = Time.new
      parse_stations(rest_client.get.body)
    rescue SocketError
      raise StationListUnavailable
    end

    def parse_stations(raw)
      station_hash = JSON.parse(raw)[stations_root]
      station_hash.map do |raw_station|
        AltaBikes::Station.new(raw_station)
      end
    end

    def rest_client
      RestClient::Resource.new(json_url)
    end
  end
end
